import Layout from "@/layout";
import {lazy, Suspense} from "react";
import {joinPath} from "@/utils/common.ts";
import {Navigate} from "react-router-dom";
import SvgIcon from "@/commponent/SvgIcon";
import {HomeOutlined} from "@ant-design/icons";
import {FiveDotLoading} from "@/components/Loading";
import {createComponentByStr} from "@/router/router_util.tsx";

export type RouterItem = {
    name?: string, // 路由名称 --- 英文
    path: string, // 路由路径
    hidden?: boolean, // 是否在菜单中隐藏
    element?: any,
    component?: any,
    redirect?: string, // 路由重定向
    children?: RouterItem[],
    meta?: {
        title?: string, // 用于标签名称
        icon?: any,
        noCache?: boolean,
        link?: null
        keepAlive?: boolean
        activeMenu?: string
    }
}

// 公共路由
export const constantRoutes: RouterItem[] = [
    {
        path: '/redirect',
        component: Layout,
        hidden: true,
        children: [
            {
                path: '/redirect/:path(.*)',
                component: lazy(() => import('@/pages/redirect/index'))
            }
        ]
    },
    {
        path: '',
        component: Layout,
        children: [
            {
                path: '/',
                element: <Navigate to={"/index"}/>
            },
            {
                path: '/index',
                component: lazy(() => import('@/pages/home/index')),
                name: 'Index',
                meta: {title: '首页', icon: 'dashboard'}
            },
            {
                path: '/system/personalCenter',
                name: 'PersonalCenter',
                hidden: true,
                component: lazy(() => import('@/pages/system/personalCenter')),
                meta: {title: '个人中心'}
            },
            {
                path: '/system/role/assigningPermissions',
                name: 'AssigningPermissions',
                hidden: true,
                component: lazy(() => import('@/pages/system/role/assigningPermissions')),
                meta: {title: '分配权限'}
            }
        ]
    },
    {
        path: '/text',
        component: lazy(() => import('@/pages/text/upload/index'))
    },
    {
        path: "/login",
        hidden: true,
        component: lazy(() => import("@/pages/login")),
    },
    {
        path: "/qrCodeLogin",
        hidden: true,
        component: lazy(() => import("@/pages/login/qrCode")),
    },
    // {
    //     path: '*',
    //     hidden: true,
    //     component: lazy(() => import('@/pages/commonPage/404')),
    // },
]

// 动态路由
export const dynamicRouter: RouterItem[] = [
    {
        path: '',
        component: Layout,
        children: [
            {
                path: '/blog/articles/edit/:artId',
                name: 'BlogArticleEdit',
                component: lazy(() => import('@/pages/blog/articles/editArticle.tsx')),
                meta: {title: '编辑文章'}
            },
            {
                path: '/blog/articles/picture/:artId',
                name: 'BlogArticlePicture',
                component: lazy(() => import('@/pages/blog/articles/pictureArticle.tsx')),
            },

        ]
    },

]


// 使用路由 将上面的路由编译成可以使用的路由对象并且将其注册到路由表中
export function createRouters(routers: any) {
    const resultRouters: any[] = [];
    // 1. 合并路由
    const allRouters = [...routers]
    const _createRouter = (routers: any, parentPath: string) => {
        const _menuRouters: any[] = []
        routers.forEach((router: any) => {
            // 3. 生成菜单
            const routerItem: any = {
                element: router.element,
                path: joinPath(parentPath, router.path),
                Component: createComponent(router.component),
            }
            if (router.children && router?.children.length > 0) {
                routerItem.children = _createRouter(router.children, router.path)
            } else {
                delete routerItem["children"]
            }
            _menuRouters.push(routerItem)
        });
        return _menuRouters
    }
    // 2. 过滤路由，生成菜单
    allRouters.forEach((router: any) => {
        // 3. 生成菜单
        const routerItem: any = {
            element: router.element,
            path: router.path,
            Component: createComponent(router.component),
        }
        if (router.children && router?.children.length > 0) {
            routerItem.children = _createRouter(router.children, router.path)
        } else {
            delete routerItem["children"]
        }
        resultRouters.push(routerItem)
    });
    return resultRouters
}

// 获取菜单信息
// 在 Layout 目录下的都是 menu 数据
export function createMenus(routers: any) {
    const resultMenus: any[] = [];
    // 1. 合并路由
    const allRouters = [...routers]
    const routerToMenu = (router: RouterItem, parentPath: string) => {
        const meta = router.meta || {}
        let menuItem: any = {
            key: joinPath(parentPath, router.path),
            label: meta.title,
            icon: null,
            children: [],
            path: joinPath(parentPath, router.path),
            name: router.name,
            meta: {
                title: meta.title,
                icon: meta.icon,
                noCache: meta.noCache,
                link: meta.link,
                keepAlive: meta.keepAlive,
                activeMenu: meta.activeMenu
            },
        }
        if (meta.icon) {
            menuItem.icon = <SvgIcon name={meta.icon} size={12}/>
        } else {
            delete menuItem["icon"]
        }
        return menuItem
    }
    const _createSidebarMenu = (routers: any, parentPath: string) => {
        const _menuRouters: any[] = []
        routers.forEach((router: any) => {
            if (router.hidden != null && router.hidden) return
            // 3. 生成菜单
            const menu: any = routerToMenu(router, parentPath)
            if (router.children !== null && router.children && router?.children.length > 0) {
                menu.children = _createSidebarMenu(router.children, router.path)
            } else {
                delete menu["children"]
            }
            _menuRouters.push(menu)
        });
        return _menuRouters
    }
    // 2. 过滤路由，生成菜单
    allRouters.forEach((router: any) => {
        if (router.hidden != null && router.hidden) return
        // 3. 生成菜单
        const menu: any = routerToMenu(router, '')
        if (router.children !== null && router.children && router?.children.length > 0) {
            menu.children = _createSidebarMenu(router.children, router.path)
        } else {
            delete menu["children"]
        }
        resultMenus.push(menu)
    });
    return resultMenus
}


export function createTagViews(routers: any) {
    const resultMenus: any[] = [];
    // 1. 合并路由
    const allRouters = [...routers]
    const routerToMenu = (router: RouterItem, parentPath: string) => {
        const meta = router.meta || {}
        let menuItem: any = {
            key: joinPath(parentPath, router.path),
            label: meta.title,
            children: [],
            path: joinPath(parentPath, router.path),
            name: router.name,
            meta: {
                title: meta.title,
                noCache: meta.noCache,
                link: meta.link,
                keepAlive: meta.keepAlive,
                activeMenu: meta.activeMenu
            },
        }
        return menuItem
    }
    const _createSidebarMenu = (routers: any, parentPath: string) => {
        const _menuRouters: any[] = []
        routers.forEach((router: any) => {
            if (router.hidden != null && router.hidden) return
            // 3. 生成菜单
            const menu: any = routerToMenu(router, parentPath)
            if (router.children !== null && router.children && router?.children.length > 0) {
                menu.children = _createSidebarMenu(router.children, router.path)
            } else {
                delete menu["children"]
            }
            _menuRouters.push(menu)
        });
        return _menuRouters
    }
    // 2. 过滤路由，生成菜单
    allRouters.forEach((router: any) => {
        if (router.hidden != null && router.hidden) return
        // 3. 生成菜单
        const menu: any = routerToMenu(router, '')
        if (router.children !== null && router.children && router?.children.length > 0) {
            menu.children = _createSidebarMenu(router.children, router.path)
        } else {
            delete menu["children"]
        }
        resultMenus.push(menu)
    });
    return resultMenus
}


export function LazySupport(component: any) {
    const Component = component
    return <Suspense fallback={<FiveDotLoading/>}>
        <Component/>
    </Suspense>
}

// 根据 components 生成对应的 Component
export function createComponent(component: any) {



    const Module = lazy(() => {
        return new Promise((resolve) => {
            import(`@/pages/${component}.tsx`)
                .then((res) => resolve(res))
                .catch((err) => {
                    //@ts-ignore
                    resolve(import(`@/pages/commonPage/404.tsx`))
                    console.log(err)
                })
        })
    })


    if (!component) return null
    if (component === 'Layout') {
        return Layout
    }
    // 判断组件是否为字符串，如果是则使用 loadView 加载
    else if (typeof component === 'string') {
        // return LazySupport(lazy(() => import(`@/pages/${component}.tsx`)))}
        // return lazy(() => import(`@/pages/${component}.tsx`))
        return Module
        // return lazy(() => createComponentByStr(component))
    }
    return component
}

// 根据 components 生成对应的 Component
export function createElement(component: any) {
    if (!component) return null
    if (component === 'Layout') {
        return Layout
    }
    // 判断组件是否为字符串，如果是则使用 loadView 加载
    else if (typeof component === 'string') {
        return LazySupport(lazy(() => import(`@/pages/${component}.tsx`)))
    }
    // return lazy(() => import(`@/pages/${component}.tsx`))}
    return component
}


// 根据 path 得到对应的面包屑的数据
function createBreadcrumb(routers: any) {
    const breadcrumbMap: Map<string, any[]> = new Map();
    const _createBreadcrumb = (routers: any, parentPath: string, parentTitle: string[]) => {
        routers.map((router: any) => {
            const lastPath = router.path ? joinPath(parentPath, router.path) : parentPath
            const lastTitle = router.title ? [...parentTitle, router.title] : parentTitle
            if (router.children && router.children.length > 0) {
                _createBreadcrumb(router.children, lastPath, lastTitle)
            } else {
                breadcrumbMap.set(lastPath, lastTitle)
            }
        })
    }
    routers.map((router: any) => {
        if (router.path === "/") {
            _createBreadcrumb(router.children, router.path, [router.title])
        }
    })
    return breadcrumbMap;
}

export const exConstantRouters = createRouters([...constantRoutes, ...dynamicRouter]);
export const blogMenus = createMenus(constantRoutes);
export const blogBreadcrumb = createBreadcrumb(constantRoutes);
